package cae.logic.reminder;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import org.apache.log4j.Logger;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class CaeReminderManager implements Runnable
{
	private static CaeReminderManager instance;
	private static final String FILE = "reminders.xml";
	private List<CaeReminder> reminders;
	private static XStream xstream = new XStream(new DomDriver());
	private static Logger logger = Logger.getLogger(CaeReminderManager.class);
	
	private CaeReminderManager()
	{
		xstream.alias("reminder", CaeReminder.class);
		load();
	}
	
	public static CaeReminderManager getInstance()
	{
		if(instance == null)
			instance = new CaeReminderManager();
		return instance;
	}
	
	@SuppressWarnings("unchecked")
	private void load()
	{
		try
		{
			InputStream file = new FileInputStream(FILE);
			reminders = (List<CaeReminder>)xstream.fromXML(file);
			file.close();
		}
		catch(Exception e)
		{
			logger.fatal("Error en la carga del archivo de reminders ", e);
			throw new RuntimeException("Error en la carga del archivo de reminders ", e);
		}
	}
	
	/*private void save()
	{
		try
		{
			OutputStream file = new FileOutputStream(FILE);
			xstream.toXML(reminders, file);
			file.close();
		}
		catch(Exception e)
		{
			logger.fatal("Error en la escritura del archivo de destinations ", e);
			throw new RuntimeException("Error en la escritura del archivo de destinations ", e);
		}
	}*/

	public void run() 
	{
		while(true)
		{
			Calendar actual = Calendar.getInstance();
			int anio = actual.get(Calendar.YEAR);
			int mes = actual.get(Calendar.MONTH);
			int dia = actual.get(Calendar.DAY_OF_MONTH);
			
			System.out.println("actual: " + actual.getTime() );
			
			try 
			{
				for (CaeReminder reminder : reminders)
				{
					Calendar reminderCalendarBegin = (Calendar)reminder.getInicio().clone();
					
					long beginMillis = reminderCalendarBegin.getTimeInMillis();
					long finishMillis = beginMillis+reminder.getDuracion();
					Calendar reminderCalendarFinish = GregorianCalendar.getInstance();
					reminderCalendarFinish.setTimeInMillis(finishMillis);
					//reminderCalendarFinish.
					
					
//System.out.println(beginMillis + " " + finishMillis);
					
					
					switch (reminder.getRepeticion())
					{
						case CaeReminder.REPETICON_DIARIA:
							System.out.println("diara..");
							reminderCalendarBegin.set(anio, mes, dia);
							reminderCalendarFinish.set(anio, mes, dia);
							
							break;
					}
					
					System.out.println("ini: " + reminderCalendarBegin.getTime() );
					System.out.println("fin: " + reminderCalendarFinish.getTime() );
					
					if( reminderCalendarFinish.before(actual) )
					{
						// FIN ANTES DE AHORA, SOLO SE PUEDE DAR SI ES SIN REPETICION, 
						//SINO ESTA MAL LA "CORRECCION"
						if(reminder.getRepeticion() != CaeReminder.REPETICON_NONE)
							throw new RuntimeException("Se quiere finalizar un recordatorio con repeticion");
						close(reminder);
					}
					else if ( actual.before(reminderCalendarBegin) )
					{
						System.out.println("Tadavia falta");
					}
					else
					{
						dispatch(reminder);
					}
				}
			
				
				
				
				Thread.sleep(60000);
			} 
			catch (InterruptedException e)
			{
				logger.error("Error al revisar reminders ", e);
			}
		}
	}

	private void dispatch(CaeReminder reminder) {
		System.out.println("ALARMA!!!");
	}

	private void close(CaeReminder reminder) {
		System.out.println("BORRAR ANTIGUO");
	}
	
	
	public static void main(String[] args) {
		CaeReminderManager m = CaeReminderManager.getInstance();
		
		Calendar cb = new GregorianCalendar(2009, 7, 8, 18, 50, 0);
		long dur = 1000*60*60*24;
		
		/*//GregorianCalendar(int year, int month, int dayOfMonth, int hourOfDay, int minute, int second) 
		m.reminders.add(new CaeReminder("hola", 0, cb, cf, CaeReminder.REPETICON_DIARIA ));
		m.save();*/
		
		m.reminders = new ArrayList<CaeReminder>();
		m.reminders.add(new CaeReminder("hola", 0, cb, dur, CaeReminder.REPETICON_DIARIA ));
		
		new Thread(m).start();
	}
	

}
